"""
@File    : RunCmd.py
@Time    : 2019/10/15 15:49
@Author  : LiuFeiYu
@Email   : liufeiyu@sunrise.net
@Software: PyCharm
"""
import os
import sys
import pytest
import Common.Consts
from Common import LogCof, ShellHelp
from Common.ConnectJenkins import ConnectJenkins
from Common.ConnectJira import *
from Settings import Config


def mkdir(path):
    # 引入模块
    # 去除首位空格
    path = path.strip()

    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    is_exists = os.path.exists(path)

    # 判断结果
    if not is_exists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        return False


def run():
    conf = Config.Config()
    log = LogCof.MyLog()
    log.info_msg('初始化配置文件, path=' + conf.conf_path)

    # 定义测试集
    allure_list = '--allure_features=test-name'

    if self_args[0] == 'all':
        xml_report_path = f'E:\\Software\\Jenkins\\workspace\\hy-all-test\\allure-reports'
        # 创建文件夹
        mkdir(xml_report_path)
        # 准备问题单的allure报告地址
        allure_url = ConnectJenkins().allure_report_url("hy-all-test")
        # 写入配置文件
        conf.set_conf("local_jenkins", "allure_report_url", allure_url)
        print("全部模块测试！")
        print(f"allure报告地址为:{allure_url}")
        # pytest运行参数
        args = ['-s', '-q', '--no-print-logs', '--alluredir', xml_report_path]
    else:
        xml_report_path = f'E:\\Software\\Jenkins\\workspace\\{module_name.replace("_", "-")}-test\\allure-reports'
        # 创建文件夹
        mkdir(xml_report_path)
        # 准备问题单的allure报告地址
        allure_url = ConnectJenkins().allure_report_url(module_name.replace("_", "-") + "-test")
        # 写入配置文件
        conf.set_conf("local_jenkins", "allure_report_url", allure_url)
        # 转换测试地址
        enum_url_name = {
            "hy_jtgl": "jtgl_host",
            "hy_lysh": "lysh_host",
            "hy_lytc": "lytc_host",
            "hy_xxfb": "xxfb_host",
            "hy_lyjc": "lyjc_host"
        }
        old_module_name = enum_url_name.get(module_name)
        conf.set_conf('private_debug', old_module_name, env_address)
        print(f"测试地址为:{env_address} , 测试模块为:{module_name} , allure报告地址为:{allure_url}")
        print("更换测试地址成功！")
        # pytest运行参数
        args = [f'./TestCase/{module_name}', '-s', '-q', '--no-print-logs', '--alluredir', xml_report_path]

    log.info_msg('执行用例集为：%s' % allure_list)

    pytest.main(args)

    try:
        if conf.jira_issue_switch == "1":
            # 自动提交问题单,如果错误接口数量超过10,则不自动提交问题单，否则自动提交问题单
            error_num = Common.Consts.API_RESPONSE_NUMBER
            true_num = Common.Consts.API_TRUE_RESPONSE_NUMBER
            print(error_num, true_num)
            accuracy_rate = "%.2f" % (true_num / (true_num + error_num))

            if Common.Consts.API_RESPONSE_NUMBER >= 10 or float(accuracy_rate) < 0.95:
                pass
            else:
                for error in Common.Consts.API_ERROR_RESPONSE_DATA:
                    GetJiraData().create_issue(
                        project_id=error['project_id'],
                        summary=error['summary'],
                        description=error['description'],
                        assignee=error['assignee'])

    except Exception:
        log.error_msg('执行用例失败，请检查环境配置')
        raise


if __name__ == '__main__':
    self_args = sys.argv[1:]
    if self_args:
        if self_args[0] == 'help':
            ShellHelp.my_help()
        elif self_args[0] == 'show':
            test_case_module = ShellHelp.show_module()
            if len(test_case_module) == 0:
                print("当前无用例模块！")
            else:
                print("可以执行的测试用例模块有:")
                for i in test_case_module:
                    print(f"{i}")
        elif self_args[0] == 'all':
            if len(self_args) == 2:
                if self_args[1] == "1":
                    Config.Config().set_conf("company_jira", "switch", "1")
                elif self_args[1] == "0":
                    Config.Config().set_conf("company_jira", "switch", "0")
                else:
                    print('参数错误')
            elif len(self_args) == 1:
                Config.Config().set_conf("company_jira", "switch", "0")
            run()
        elif len(self_args) < 2 or len(self_args) > 3:
            print("传入参数错误！请用help获得帮助")
        else:
            env_address = self_args[0]
            module_name = self_args[1]
            if not env_address.startswith("http://"):
                print("传入环境地址有误,请重新传入")
            elif module_name not in ShellHelp.show_module():
                print("参入模块名不存在,请重新传入")
            else:
                if len(self_args) == 3:
                    if self_args[2] == "1":
                        Config.Config().set_conf("company_jira", "switch", "1")
                    elif self_args[2] == "0":
                        Config.Config().set_conf("company_jira", "switch", "0")
                    else:
                        print('参数错误')
                elif len(self_args) == 2:
                    Config.Config().set_conf("company_jira", "switch", "0")
                run()

    else:
        print("传入参数错误！请用help获得帮助")